library(survey)
library(dplyr)
library(ggplot2)

# Creating Figure 5.4 - Party differences
# Wave 1
summary(factor(mil_conf.df$Q8))
mil_conf.df$Q8a <- 0
mil_conf.df$Q8a[mil_conf.df$Q8 < 3] <- 1
summary(factor(mil_conf.df$Q8a))

mil_conf.df$DOV_ETHICAL <- NA
mil_conf.df$DOV_ETHICAL[mil_conf.df$DOV_ASSIGNMENT_A == 1] <- 0
mil_conf.df$DOV_ETHICAL[mil_conf.df$DOV_ASSIGNMENT_A == 7] <- 1
summary(factor(mil_conf.df$DOV_ETHICAL))

mil_conf.df$DOV_UNETHICAL <- NA
mil_conf.df$DOV_UNETHICAL[mil_conf.df$DOV_ASSIGNMENT_A == 1] <- 0
mil_conf.df$DOV_UNETHICAL[mil_conf.df$DOV_ASSIGNMENT_A == 8] <- 1
summary(factor(mil_conf.df$DOV_UNETHICAL))



# Creating weighted survey design objects
w1_design <-
  svydesign(
    id = ~ 1,
    weights = ~ weight,
    data = mil_conf.df
  )


# Wave 1
# dov_assignment_a == 7 - Ethical generals
ETH_d <- svyttest(Q8a~DOV_ETHICAL, w1_design[w1_design$variables$party==0])
ETH_i <- svyttest(Q8a~DOV_ETHICAL, w1_design[w1_design$variables$party==1])
ETH_r <- svyttest(Q8a~DOV_ETHICAL, w1_design[w1_design$variables$party==2])

# dov 8 - Unethical generals
UNETH_d <- svyttest(Q8a~DOV_UNETHICAL, w1_design[w1_design$variables$party==0])
UNETH_i <- svyttest(Q8a~DOV_UNETHICAL, w1_design[w1_design$variables$party==1])
UNETH_r <- svyttest(Q8a~DOV_UNETHICAL, w1_design[w1_design$variables$party==2])


pt.est <- c(ETH_d$estimate, ETH_i$estimate, ETH_r$estimate,
            UNETH_d$estimate, UNETH_i$estimate, UNETH_r$estimate)
ci.low <- c(ETH_d$conf.int[1], ETH_i$conf.int[1], ETH_r$conf.int[1], 
            UNETH_d$conf.int[1], UNETH_i$conf.int[1], UNETH_r$conf.int[1])
ci.high <- c(ETH_d$conf.int[2], ETH_i$conf.int[2], ETH_r$conf.int[2],
             UNETH_d$conf.int[2], UNETH_i$conf.int[2], UNETH_r$conf.int[2])
plot.labs <- c(" ", "Ethical\nGenerals", "  ", "   ", "Unethical\nGenerals", "    ")
df.plot <- data.frame(Treatment=plot.labs, estimate=pt.est, 
                      lower=ci.low, upper=ci.high)
df.plot$Treatment <- factor(df.plot$Treatment, levels = plot.labs)

ggplot()+
  geom_pointrange(data=df.plot, 
                  mapping = aes(x=Treatment,
                                y=estimate,
                                ymin=lower,
                                ymax=upper),
                  size = 0.5, color = c("blue","gray50","red",
                                        "blue","gray50","red"))+
  geom_hline(yintercept = 0, color = "red")+
  ylab("Difference in Means from Control Condition")+
  xlab("Treatment Condition")+
  theme_bw()
